package com.cloud.common.bean;

import com.cloud.common.util.JsonUtils;
import com.google.common.collect.Sets;
import lombok.Data;

import javax.validation.constraints.NotEmpty;
import java.util.Set;

/**
 * 会话信息
 *
 * @author fengwenjin
 */
@Data
public class SessionInfo {
    public static final String DEBUG = "debug";

    /**
     * 密钥（必填）
     */
    @NotEmpty(message = "secret not empty")
    private String secret;

    /**
     * 应用名（必填）
     */
    @NotEmpty(message = "appName not empty")
    private String appName;

    /**
     * 用户ID（必填）
     */
    @NotEmpty(message = "userId not empty")
    private String userId;

    /**
     * 昵称名
     */
    private String nickName;

    /**
     * 扩展信息
     */
    private Object extraInfo;

    /**
     * 有效秒数
     */
    private int validSeconds;

    /**
     * 刷新时间
     */
    private long refreshTime;

    /**
     * 授权资源
     */
    private Set<String> authResources = Sets.newHashSet();

    /**
     * 白名单IP
     */
    private Set<String> whitelistIps = Sets.newHashSet("*");

    /**
     * 是否跟踪
     */
    private boolean traced;

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId.toString();
    }

    public Long userId() {
        if (this.userId != null) {
            return Long.parseLong(userId);
        }
        return null;
    }

    public <T> T getExtraInfo(Class<T> clazz) {
        if (this.extraInfo != null) {
            return JsonUtils.parseObject(extraInfo.toString(), clazz);
        }
        return null;
    }

    public void setExtraInfo(Object extraInfo) {
        if (extraInfo instanceof String) {
            this.extraInfo = extraInfo;
        } else {
            this.extraInfo = JsonUtils.toJSONString(extraInfo);
        }
    }

    public static SessionInfo buildDefault() {
        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setSecret(DEBUG);
        sessionInfo.setAppName(DEBUG);
        sessionInfo.setUserId(0L);
        return sessionInfo;
    }
}
